<?php
class UnloadAction extends CommonAction {
	function _filter(&$map) {
		if ('1' !== $_SESSION [C ( 'USER_AUTH_KEY' )]) {
			$map ['unloadname'] = $_SESSION ['loginUserName'];
		}
	}
	function _before_add() {
		$userModel = M ( 'User' );
		$user = $userModel->select ();
		$this->assign ( 'user', $user );
	}
	// 删除前的业务修改
	function _before_foreverdelete() {
		$ids = $_REQUEST[ids];
		$id = explode(',',$ids);
		if(count($id)>0){
			for($i = 0;$i<count($id);$i++){
				$this->batchdelete($id[$i]);
			}
		}else{
			$this->ajaxReturn(0,'没有选中的删除项，请确认！',300);
		}
	}
    //批量删除
	function batchdelete($ids){
	
		$model = M ( 'Unload' );
		$model1 = M ( 'Customer' );
		$model2 = M ( 'ControlTable' );
		$model3 = M ( 'StoreManage' );
		$model4 = M ( 'CarrierDispatch' );
		$model5 = M ( 'Freight' );
		// 开始事务
		$model->startTrans ();
		$R3 = true;
		$result1 = true;
		$id = $ids;
		$Unload = $model->where ( 'id=' . $id )->find ();
		$orders = $Unload ['orders'];
		$ControlTable = $model2->where ( 'orders=' . $orders )->select ();
		
		if (! $ControlTable) {
			$model->rollback ();
			$this->ajaxReturn ( '0', '没有查找到对应的调度信息，删除失败!', '300' );
		} else {
			//客户ID
			$customerid = $ControlTable [0] ['customer'];
			//商品名称
			$goodname = $ControlTable [0] ['product'];
			$data ['NetLandedWeight'] = NULL; // 卸货净重
			$data ['carstat'] = "3"; // 改变车辆状态，1为可用，运送完毕
			$data ['loss'] = NULL; // 盈亏
			$Cusresult = $model1->where ( 'id=\'' . $customerid . '\'' )->find();
			if (! $Cusresult) {
				$model->rollback ();
				$this->ajaxReturn ( '0', '没有查找到对应的客户信息，删除失败!', '300' );
			} else {
				//判断是否是向仓库送货 id 1.2.3分别为东明库 南曹库 金海库
				$Cusname = $Cusresult['customername'];
				$storenameA = 'storeA';
				$storenameB = 'storeB';
				$storenameC = 'storeC';
				if($Cusname=="东明库"){
					//还原仓库吨数
					$Astoremanage = $model3->where( 'product=\'' . $ControlTable[0] ['product'] . '\' and storename=\'' . $storenameA . '\'' )->select ();
					if(!$Astoremanage){
						$model->rollback ();
						$this->ajaxReturn ( 0, '东明库不存在该商品', 300 );
					}else{
						$DStodata['stock'] = bcsub($Astoremanage[0]['stock'], $Unload ['eweight']);
						$R3 = $model3->where( 'product=\'' . $ControlTable[0] ['product'] . '\' and storename=\'' . $storenameA . '\'' )->save($DStodata);
					}
				}else{
					if($Cusname=="南曹库"){
						//
						$Astoremanage = $model3->where( 'product=\'' . $ControlTable[0] ['product'] . '\' and storename=\'' . $storenameB . '\'' )->select ();
						if(!$Astoremanage){
							$model->rollback ();
							$this->ajaxReturn ( 0, '南曹库不存在该商品', 300 );
						}else{
							$NStodata['stock'] = bcsub($Astoremanage[0]['stock'], $Unload ['eweight']);
							$R3 = $model3->where( 'product=\'' . $ControlTable[0] ['product'] . '\' and storename=\'' . $storenameB . '\'' )->save($NStodata);
						}
					}else{
						if($Cusname=="金海库"){
							//
							$Astoremanage = $model3->where( 'product=\'' . $ControlTable[0] ['product'] . '\' and storename=\'' . $storenameC . '\'' )->select ();
							if(!$Astoremanage){
								$model->rollback ();
								$this->ajaxReturn ( 0, '金海库不存在该商品', 300 );
							}else{
								$JStodata['stock'] = bcsub($Astoremanage[0]['stock'], $Unload ['eweight']);
								$R3 = $model3->where( 'product=\'' . $ControlTable[0] ['product'] . '\' and storename=\'' . $storenameC . '\'' )->save($JStodata);
							}
						}else{
							// 当客户不为仓库时还原客户已供货未供货量
							$map ['customerid'] = $customerid;
							$map ['product'] = $goodname;
							$model6 = M('CustomerGood');
							$Cusgood = $model6->where ( $map )->select ();
							
							// 判断客户是否存在该商品
							if ($Cusgood) {
								// 已供货量
								$datacustomer ['hassupply'] = bcsub ( $Cusgood[0]['hassupply'], $Unload ['eweight'], 4 );
								// 未供货量
								$datacustomer ['nosupply'] = bcsub ( $Cusgood[0]['supplyamount'], $datacustomer ['hassupply'], 4 );
								$result1 = $model6->where ($map)->save ( $datacustomer );
							} else {
								$model->rollback ();
								$this->ajaxReturn ( 0, '对应的客户不存在该商品', 300 );
							}
						}
					}
				}
			
				// 租车信息还原
				$mapc ['freight'] = NULL;
				$mapc ['uweight'] = NULL;
				$result2 = $model4->where ( 'orders=' . $orders )->save ( $mapc );
			}
			// 还原调度表中卸货净重，盈亏，车辆状态信息
			$result3 = $model2->where ( 'orders=' . $orders )->save ( $data );
		}
		if (($result2!==false) && ($result1!==false) && ($result3!==false)&&($R3!==false)) {
			$model->commit ();
		} else {
			$model->rollback ();
			$this->ajaxReturn ( '0', '删除失败,请联系管理员!', '300' );
		}
	}
	
	// 显示符合条件的调度信息
	function QueryUnload() {
		$model1 = M ( 'ControlTable' );
		// 车牌号
		$carno = $_REQUEST ['carno'];
		// 接车人
		$unloadname = $_REQUEST ['unloadname'];
		// 限制条件
		$map ['carno'] = $carno;
		$map ['carstat'] = 3;
		$map ['removed'] = 1;
		if ('1' !== $_SESSION [C ( 'USER_AUTH_KEY' )]) {
			$map ['userid'] = $_REQUEST ['fullname'];
		}
		$ControlTable = $model1->where ( $map )->select ();
		if ($ControlTable) {
			$model3 = M ( "Carrier" );
			$Carrier = $model3->select ();
			$model2 = M ( "Provider" );
			$Provider = $model2->select ();
			$model4 = M ( "Customer" );
			$Customer = $model4->select ();
			$this->assign ( 'carr', $Carrier );
			$this->assign ( 'provider', $Provider );
			$this->assign ( 'customer', $Customer );
			$this->assign ( 'list', $ControlTable );
			$this->display ();
		} else {
			$this->ajaxReturn ( 0, "没有相关的车辆调度或该车调度信息已经卸过车了！", 300 );
		}
	}
	// 输入吨数信息页面
	function dialogUnload() {
		$id = $_REQUEST ['id'];
		$this->assign ( 'id', $id );
		
		$model2 = M ( "Provider" );
		$Provider = $model2->select ();
		$this->assign ( 'list2', $Provider );
		// 客户信息
		$model4 = M ( "ContractLog" );
		$ContractLog = $model4->where('status>=0 and type = 1 ')->select ();
		$this->assign ( 'list4', $ContractLog);
		$userModel = M ( 'User' );
		$user = $userModel->query('SELECT  *  FROM  `mlt_user` ORDER BY CONVERT( fullname USING gbk ) COLLATE gbk_chinese_ci ASC;');
		$this->assign ( 'user', $user );
		$freightModel = M ( 'Freight' );
		$freight = $freightModel->distinct ( true )->field ( 'startaddress' )->select ();
		$end = $freightModel->distinct ( true )->field ( 'endaddress' )->select ();
		$this->assign ( 'freight', $freight );
		$this->assign ( 'end', $end );
		$this->display ();
	}
	
	// 保存卸车信息
	function insert() {
		$id = $_REQUEST ['id'];
		$eweight = $_REQUEST ['eweight']; // 本次客户卸货净重
		$seteweight = $_REQUEST ['seteweight']; // 运费结算净重
		$unloadname = $_REQUEST ['unloadname'];//卸车人
		$unloadtime = $_REQUEST ['unloadtime'];//卸车时间
		$carstat = $_REQUEST ['carstat'];//是否卸完成
		$SecidAndConLogid = explode(',', $_REQUEST['contractlogid']);
		$model = M ( 'ControlTable' );
		$model1 = M ( 'Unload' );
		$model1->startTrans();
		$RCTL1 = true;
		$RCTL2 = true;
		$RCT = true;
		$Tableresult = true;
		$r4 = true;
		$RCusT = true;
		$RDdatage = true;
		$model4 = M ( 'CarrierDispatch' );
		$model6 = M ( "Provider" );
		$model3 = M ( 'StoreManage' );
		$model5 = M ( 'Freight' );
		$model7 = M ( 'ContractLog' );
		// 根据ID查找对应的调度记录
		$Con = $model->find ( $id );
		// 是否已经付款
		if ($Con ['payondelivery'] == 1) {
			$model1->rollback();
			$this->ajaxReturn ( '0', '该车调度信息还未付款，请联系财务部门!', '300' );
		} else {
			// 盈亏
			$loss = bcsub ( $eweight, $Con ['Factorynetweight'], 4 );
			// 订单号
			$orders = $Con ['orders'];
			// 车牌号
			$carno = $Con ['carno'];
			// 客户
			$customername = $Con ['customer'];
			// 商品名称
			$goodname = $Con ['product'];
			// 更新ControlTable数据存入data
			//如果还需要去其它客户卸车
			if("1"==$carstat){
				$data ['NetLandedWeight'] = $eweight; // 卸货净重
				$data ['carstat'] = "1"; // 改变车辆状态，1为可用，运送完毕
				$data ['loss'] = "0"; // 盈亏
				$data ['seteweight'] = $seteweight; // 运费结算净重
				$data['Factorynetweight'] =$eweight;
				//计算差值
				$Dvalue = bcsub($Con ['Factorynetweight'],$eweight,4);
				//更改拟定调度客户的信息
		        if($_REQUEST['contractlogid']!==""){
		        	$newControlTabledata['customer'] =$SecidAndConLogid[1];
		        	//选择下一个客户后 修改对应客户拟定调度的已调度数
		        	$list7 = $model7->where("id=".$SecidAndConLogid[0])->select();
		        	//alshipment:已调度量
		        	$data7['alshipment'] = bcadd($Dvalue,$list7[0]['alshipment'],4);
		        	$data7['status'] = ($data7['alshipment']/$list7[0]['capacity'])*100;
		        	$RCTL1 = $model7->where("id=".$SecidAndConLogid[0])->save($data7);
		        }
		        //修改之前客户的拟定调度数
		        $list8 = $model7->where("id=".$Con['contractlogid'])->select();
		        $data8['alshipment'] = bcsub($list8[0]['alshipment'],$Dvalue,4);
		        $data8['status'] = ($data8['alshipment']/$list8[0]['capacity'])*100;
		        $RCTL2 = $model7->where("id=".$Con['contractlogid'])->save($data8);
		        if($_REQUEST['userid']){
		        	$newControlTabledata['userid'] =$_REQUEST['userid'];
		        }
				if($_REQUEST['start']){
					$newControlTabledata['start'] =$_REQUEST['start'];
				}
				if($_REQUEST['destination']){
					$newControlTabledata['destination'] =$_REQUEST['destination'];
				}
				if($_REQUEST['note']){
					$newControlTabledata['note'] =$_REQUEST['note'];
				}
				$newControlTabledata['orders'] =date('YmdHis');
				$newControlTabledata['contractno'] =$Con['contractno'];
				$newControlTabledata['shipper'] =$Con['shipper'];
				$newControlTabledata['provider'] =$Con['provider'];
				$newControlTabledata['carrier'] =$Con['carrier'];
				$newControlTabledata['carno'] =$Con['carno'];
				$newControlTabledata['carstat'] ="3";
				$newControlTabledata['sweight'] ="";//皮重
				$newControlTabledata['eweight'] ="";//毛重
				$newControlTabledata['product'] =$Con['product'];
				$newControlTabledata['warehouse'] =$Con['warehouse'];
				$newControlTabledata['supplier'] =$Con['supplier'];
				$newControlTabledata['notshipment'] =$Con['notshipment'];
				$newControlTabledata['alshipment'] =$Con['alshipment'];
				$newControlTabledata['spare'] =$Con['spare'];
				$newControlTabledata['type'] =$Con['type'];
				$newControlTabledata['loss'] ="";
				$newControlTabledata['Factorynetweight'] =bcsub($Con ['Factorynetweight'], $eweight,4);
				$newControlTabledata['NetLandedWeight'] ="";
				$newControlTabledata['controldate'] =date('YmdHis');
				$newControlTabledata['seteweight'] ="";
				$newControlTabledata['payondelivery'] =$Con['payondelivery'];
				$newControlTabledata['operator'] =$Con['operator'];
				$newControlTabledata['removed'] =$Con['removed'];
				$newControlTabledata['contractlogid'] =$SecidAndConLogid[0];
				$newControlTabledata['tocontractlogid'] =$Con['tocontractlogid'];
				
				//修改供应商的拟定调度信息
				
				
				$RCT = $model->add($newControlTabledata);
			}else{
				$data ['NetLandedWeight'] = $eweight; // 卸货净重
				$data ['carstat'] = "1"; // 改变车辆状态，1为可用，运送完毕
				$data ['loss'] = $loss; // 盈亏
				$data ['seteweight'] = $seteweight; // 运费结算净重卸车记录存入dataud
			}
			$dataud ['orders'] = $orders;
			$dataud ['carno'] = $carno;
			$dataud ['unloadname'] = $unloadname;
			$dataud ['unloadtime'] = $unloadtime;
			$dataud ['eweight'] = $eweight;
			$dataud ['seteweight'] = $seteweight;
			
			// 修改客户表已供货信息
			$model2 = M ( 'CustomerGood' );
			$model8 = M ( 'Customer' );
			$customer = $model8->find ( $customername );
			$map ['customerid'] = $customername;
			$map ['product'] = $goodname;
			$cusgood = $model2->where ( $map )->select ();
			// 判断客户是否存在该商品
			if ($cusgood) {
				// 已供货量
				$datacusgood ['hassupply'] = bcadd ( $eweight, $cusgood [0] ['hassupply'], 4 );
				// 未供货量
				$datacusgood ['nosupply'] = bcsub ( $cusgood [0] ['supplyamount'], $datacusgood ['hassupply'], 4 );
			} else {
				if ($customer ['customername'] !== '东明库' && $customer ['customername'] !== '南曹库' && $customer ['customername'] !== '金海库') {
					$model1->rollback();
					$this->ajaxReturn ( 0, '对应的客户不存在该商品', 300 );
				}
			}
			// 修改租车信息运费，等于单价乘以卸货净重,信息存入mapc
			$mapf ['startaddress'] = $Con ['start']; // 起始地
			$mapf ['endaddress'] = $Con ['destination']; // 目的地
			$mapf ['carrierid'] = $Con ['carrier']; // 承运方ID
			$lists = $model5->where ( $mapf )->select ();
			if (! empty ( $lists )) {
				$unitprice = $lists [0] ['unitprice'];
				$total = $unitprice * $seteweight;
			} else {
				$total = "";
			}
			$mapc ['freight'] = $total; // 运费
			$mapc ['uweight'] = $seteweight;
			
			// 更新仓库信息
			$storenameA = 'storeA';
			$storenameB = 'storeB';
			$storenameC = 'storeC';
			// 区别东明库与南曹库
			$providername = $model6->where ( 'id=' . $Con ['provider'] )->find ();
			if ($customer ['customername'] == "东明库" || $Con ['destination'] == "东明库") {
				$Astoremanage = $model3->where ( 'product=\'' . $Con ['product'] . '\' and storename=\'' . $storenameA . '\'' )->select ();
				if (! $Astoremanage) {
					$model1->rollback();
					$this->ajaxReturn ( 0, '东明库不存在该商品', 300 );
				} else {
					$Ddatage ['stock'] = bcadd($Astoremanage [0] ['stock'] , $eweight,4);
				}
			}			// else {
			// if ($Con['start'] == "东明库" || $providername == "东明库") {
			// $Astoremanage = $model3->where ( 'product=\'' . $Con['product'] .
			// '\' and storename=\''.$storenameA.'\'' )->select ();
			// $Ddatage ['stock'] = bcsub($Astoremanage [0]
			// ['stock'],$eweight,4);
			// }
			// }
			elseif ($customer ['customername'] == "南曹库" || $Con ['destination'] == "南曹库") {
				$Bstoremanage = $model3->where ( 'product=\'' . $Con ['product'] . '\' and storename=\'' . $storenameB . '\'' )->select ();
				if (! $Bstoremanage) {
					$model1->rollback();
					$this->ajaxReturn ( 0, '南曹库不存在该商品', 300 );
				} else {
					$Ndatage ['stock'] = bcadd($Bstoremanage [0] ['stock'],$eweight,4);
				}
			} elseif ($customer ['customername'] == "金海库" || $Con ['destination'] == "金海库") {
				$Cstoremanage = $model3->where ( 'product=\'' . $Con ['product'] . '\' and storename=\'' . $storenameC . '\'' )->select ();
				if (! $Cstoremanage) {
					$model1->rollback();
					$this->ajaxReturn ( 0, '金海库不存在该商品', 300 );
				} else {
					$Jdatage ['stock'] = bcadd($Cstoremanage [0] ['stock'],$eweight,4);
				}
			}
			// else {
			// if ($Con['start'] == "南曹库" || $providername == "南曹库") {
			// $Bstoremanage = $model3->where ( 'product=\'' . $Con['product'] .
			// '\' and storename=\''.$storenameB.'\'' )->select ();
			// $Ndatage ['stock'] = bcsub($Bstoremanage [0]
			// ['stock'],$eweight,4);
			// }
			// }
			// 判断是否重复卸车
			$Unloaddata = $model1->getByOrders ( $orders );
			if ($Unloaddata) {
				$model1->rollback();
				$this->ajaxReturn ( '0', '该车调度信息已经卸过车了!', '300' );
			} else {
				// 高级管理员所有卸车权限
				$model9 = M ( 'User' );
				$userid = $model9->where ( 'fullname=\'' . $unloadname . '\'' )->select ();
				// 判断是否符合为制定的人卸车
				if (($unloadname == $Con ['userid']) || ($userid [0] ['id'] == '1')) {
					$Tableresult = $model->where ( 'id=' . $id )->save ( $data );
					$r4 = $model4->where ( 'orders=' . $orders )->save ( $mapc );
					// 修改仓库信息
					if ($Ddatage) {
						$RDdatage = $StoreManageresult = $model3->where ( 'product=\'' . $Con ['product'] . '\' and storename=\'' . $storenameA . '\'' )->save ( $Ddatage );
					} elseif ($Ndatage) {
						$RDdatage = $StoreManageresult = $model3->where ( 'product=\'' . $Con ['product'] . '\' and storename=\'' . $storenameB . '\'' )->save ( $Ndatage );
					} elseif ($Jdatage) {
						$RDdatage = $StoreManageresult = $model3->where ( 'product=\'' . $Con ['product'] . '\' and storename=\'' . $storenameC . '\'' )->save ( $Jdatage );
					} else {
						// 修改客户表已供货信息
						$RCusT = $model2->where ( 'id=' . $cusgood [0] ['id'] )->save ( $datacusgood );
					}
					// 增加卸货记录
					$list = $model1->add ( $dataud );
					// 写入调度信息
					$model10 = M ( 'ControlLog' );
					$datalog ['control'] = $Con ['id'];
					$datalog ['logtime'] = $unloadtime;
					$datalog ['log'] = '订单号：' . $orders . '被' . $unloadname . '卸车.客户卸货净重:' . $eweight . '运费结算净重:' . $seteweight;
					$R6 = $model10->add ( $datalog );
					if (($list!==false)&&($RCusT!==false)&&($r4!==false)&&($R6!==false)&&($RCT!==false)&&($RCTL1!==false)&&($RCTL2!==false)&&($RDdatage!==false)) { 
						$model1->commit();// 保存成功
						$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
						$this->ajaxReturn ( 1, '新增成功!', 200 );
					} else {
						$model1->rollback();
						// 失败提示
						$this->ajaxReturn ( 1, '新增失败!', 300 );
					}
				} else {
					$model1->rollback();
					$this->ajaxReturn ( 0, "没有相关接车人的卸车信息，请确认！", 300 );
				}
			}
		}
	}
	public function udselect() {
		// 查找符合订单号的记录
		$model = M ( "ControlTable" );
		$orders = $_POST ['orders'];
		$vo = $model->where ( 'orders=' . $orders )->find ();
		if ($vo == true) {
			$this->assign ( 'vo', $vo );
			$this->display ();
		} else {
			$this->ajaxReturn ( '0', '该订单不存在!', 300 );
		}
	}
	public function update() {
		$model = M ( "ControlTable" );
		$model1 = M ( 'Unload' );
		$orders = $_POST ['orders'];
		$eweight = $_REQUEST ['eweight'];
		if (empty ( $eweight )) {
			$this->ajaxReturn ( '0', '请输入卸货净重!', '300' );
		} else {
			$Unloaddata = $model1->getByOrders ( $orders );
			if ($Unloaddata) {
				$this->ajaxReturn ( '0', '该订单号已经卸过车了!', '300' );
			} else {
				$model->where ( 'orders="' . $orders . '"' )->setField ( 'eweight', $eweight );
				$upload = M ( "Unload" );
				$ControlTable = $model->where ( 'orders=' . $orders )->find ();
				$data ['orders'] = $ControlTable ['orders'];
				$data ['unloadname'] = $ControlTable ['userid'];
				$data ['carno'] = $ControlTable ['carno'];
				$data ['unloadtime'] = date ( 'Y-m-d H:i:s' );
				$data ['eweight'] = $ControlTable ['eweight'];
				$data ['start'] = $ControlTable ['start'];
				$data ['destination'] = $ControlTable ['destination'];
				$result = $model1->add ( $data );
				if ($result) {
					$this->ajaxReturn ( 1, '信息添加成功！', 200 );
					$this->assign ( 'jumpUrl', 'Unload/index' );
				} else {
					$this->ajaxReturn ( 1, '信息添加失败！', 300 );
				}
			}
		}
	}
}
?>